/**
 * Created by jyc on 2016/3/28.
 */

// 选项卡是否正被点击标识
var switch_tab_clicking = false;

// Wait until the DOM has loaded before querying the document
$(document).ready(function() {
    var leftTimeTop = $(".main-table>thead>tr").height()-5;
    $(".left-time-list ul").css("padding-top",leftTimeTop);
    $(".venuesNoticeName").height($(".venuesNotice").height());
     baseHeight = $('.venues-tab').outerHeight();
    
    if(!isIELow()){
      $('.venues-tab').smartFloat();
    }

    $('.venues-tab').each(function() {
        // For each set of tabs, we want to keep track of
        // which tab is active and its associated content
        var $active, $content;
        var $links = $(this).find('li');
        // If the location.hash matches one of the links, use that as the active tab.
        // If no match is found, use the first link as the initial active tab.
        $active = $($links.filter('[data="' + location.hash + '"]')[0] || $links[0]);
        activeTab($active.attr('data'));
        
        // Bind the click event handler
        $(this).on('click','li',function(e) {  
            switch_tab_clicking = true;
            activeTab($(this).attr('data'))

            insideJump($(this).attr('data'));

            // Prevent the anchor's default click action
            e.preventDefault();
        });
    });
    
    $(".display-book-date").each(function(){
        var ret = trans2WeekDayWithYear($(this).attr("date-time"));
        $(this).text(ret);
    })

    $(".display-unpaid-holder").each(function(){
        var startTime = transTimeFormart($(this).attr("start_time"));
        var endTime = transTimeFormart($(this).attr("end_time"));
        var origValue = $(this).attr("place_holder");
        if (startTime != "" && endTime != "" && origValue != ""){
          $(this).append('<strong>'+startTime+'-'+endTime+' '+origValue+'</strong>');
        }
      })

    init();
    scrollActiveSwitchTab();
  });

function init(){
    $(".single").each(function() {
      $(this).off().on('click', function(e) {

      if($(".dueOrderName")[0] != null){
          checkOrderDueCount(BookingFunc, $(this));
          return;
      }

      BookingFunc($(this));
      
      });
      
      $(this).hover (
        function(){
          toggleMark($(this),"true"); 
        },function(){
           toggleMark($(this),"false"); 
        }
      );
  });
  
    //使用powerFloat显示浮动提示框
    $(".single").powerFloat(
      {
        eventType: "hover", targetMode: "remind", targetAttr: "place_holder", position: "5-7", showDelay: "0",hoverHold:"false"
      }
    );
}
    
  
function scrollActiveSwitchTab(){

  $(window).scroll(function(){
    if (switch_tab_clicking) {
      // 选择卡正被点击，屏蔽scroll事件
      switch_tab_clicking = false;
      return false;
    }
    
    var scrolls = $(this).scrollTop();
    var ids = ['booking', 'detail', 'comment','nearby']; // 定位的元素id列表
    var length = ids.length;

    for(var i = 0; i< length; i++){
      var element = document.getElementById(ids[i]);
      if(element) {
        if(i == 0 && scrolls < getElementTop(element) - baseHeight){
          activeTab(ids[i]);
          break;
        }
        
        if(scrolls > getElementTop(element) - baseHeight) {
          activeTab(ids[i]);
        } 
      }
    }
  });

}

function getElementTop(element) {
  var offset = element.offsetTop;
  if(element.offsetParent != null) offset += getElementTop(element.offsetParent);
  return offset;
}

function toggleBooking(single){
  var orig_number = parseInt($(".court-display>span.number").text());
  var orig_price = parseFloat($(".price-display>span.number").text().slice(0, -1));
  
  if (single.children("span").hasClass("chosen")) 
  {
      var txt = single.attr("place_holder");
      $('.right-order-plane .info li.court').each(function() {
          if ($(this).text() == txt) {
              $(this).remove();
          }
      });
      
      if (orig_number > 0) {
          orig_number--;
      } 
      
      if (orig_price >= parseFloat(single.attr("price"))) {
          orig_price = parseFloat((orig_price - parseFloat(single.attr("price"))).toFixed(2));
      }

      if (orig_number == 0) {
        $(".selected-booking>li.none").show();
      };
  } else {

      var input_str1 = "<input type=hidden name=goods_id value="+ single.attr("goods_id").split(',')[0]+">";
      var input_str2 = '<input type=hidden name=goods_list['+single.attr("goods_id").split(',')[0]+'] value="'+ single.attr("place_holder")+'">';

      $(".selected-booking").append("<li class=court>" + single.attr("place_holder") + input_str1 + input_str2+ "</li>");

      orig_number++;
      orig_price = parseFloat((orig_price + parseFloat(single.attr("price"))).toFixed(2));

      if (orig_number > 0) {
        $(".selected-booking>li.none").hide();
      };
  }
  
  single.children("span").toggleClass("chosen");
  
  $(".court-display>span.number").text(orig_number);
  $(".price-display>span.number").text(orig_price + '元');

  if (orig_number > 0){
    if (!$(".info>a.submit-button").hasClass("active")) {
      $(".info>a.submit-button").addClass("active");
    };
    $(".append-msg").show();
  } else {
    $(".append-msg").hide();
    $(".info>a.submit-button").removeClass("active");
  }

}

function toggleMark(single,action) {
  if(!single.children("span").hasClass("chosen")) {
     var typeClass = "highlight";
     if (single.attr("status") != "0"){
        typeClass = "half-mark";
     }

     if(action=="true"){
      single.children("span").addClass(typeClass); 
     } else {
      single.children("span").removeClass(typeClass);  
     }
  }

  //行遍历 single.index() 横向最大值
  var cells = single.parent().find("td");
  for (var i = 0; i < single.index(); i++) {
    setSingleCellStyle($(cells[i]),action);
  }

  //列遍历 single.parent().index() 纵向最大值
  var rows = $("http://www.quyundong.com/gosport/venues/js/tr.rows");
  for (var j = 0; j < single.parent().index(); j++) {
     var cells = $(rows[j]).find("td");
     setSingleCellStyle($(cells[single.index()]),action);
  }
}

function setSingleCellStyle(cell,action){
  var typeClass = "";
  if (cell.attr("status") != "0") {
    typeClass = "half-mark";
  } else if (!cell.children("span").hasClass("chosen")) {
    typeClass = "mark";
  }
  
  if(action == "true"){  
    cell.children("span").addClass(typeClass);
  } else {
    cell.children("span").removeClass(typeClass);
  }
}

function BookingFunc(cell){
  if (cell.attr("status") == "0") 
  {
    //将判断选择场次提前
    var isSelected = (cell.children("span").hasClass("chosen"));
    var orig_number = parseInt($(".court-display>span.number").text());
    if (!isSelected && orig_number >= 4) {
        openCommonAlert("您选择的场次太多，请分两次下单结算！",null,"确定",null,null);
        return;
    }
    if (cell.attr("group_ids")) {
      checkGroupBooking(cell);
    } else {

      var min_hour = $('input[name=min_hour]').val();
      if (min_hour >= 2) { 
        ret = checkMustTwoHour(cell,min_hour);
        if (!ret) {
          openCommonAlert("不足两小时，无法预订！",null,"确定",null,null);
        }
        
        return;
      };
    }
    toggleBooking(cell);
  }
};

function checkMustTwoHour(single,min_hour){
  var rows = $("http://www.quyundong.com/gosport/venues/js/tr.rows");
  var isDone = false;
  var isChosen = (single.children("span").hasClass("chosen"));
  var bind_goods_ids = new Array();
  var bind_cells = new Array();
  var lowIndex = single.parent().index() - 1
  var highIndex = single.parent().index() + 1;
  if(single.parent().index() + 1 >= rows.length) {
    highIndex = single.parent().index();
  }
  if(single.parent().index() - 1 < 0){
    lowIndex = single.parent().index();
  }

  for(i = highIndex;i >= lowIndex;i--){
    var cells = $(rows[i]).find("td");
    var cell = $(cells[single.index()]);
    if ((!isChosen && cell.attr("status") == "0" && !cell.children("span").hasClass('chosen')) ||
        (isChosen && cell.children("span").hasClass('chosen') && cell.attr("bind_goods_ids") == single.attr("bind_goods_ids"))
    ){
      bind_goods_ids.push(cell.attr("goods_id").split(',')[0]);
      bind_cells.push(cell);
    }

    if (bind_goods_ids.length >= min_hour) {
      isDone = true;
      break;
    };

  }

  if (isDone) {

    for(i in bind_cells){
      bind_cells[i].attr("bind_goods_ids",bind_goods_ids);
      toggleBooking(bind_cells[i]);
    }
  }

  return isDone;
}

function checkGroupBooking(single){
  //列遍历 single.parent().index() 纵向最大值
  var rows = $("http://www.quyundong.com/gosport/venues/js/tr.rows");
  rows.each(function(){
    var cells = $(this).find("td");
    var cell = $(cells[single.index()]);

    //跳过本条目
    if (cell.attr("goods_id") == single.attr("goods_id")){
        return true;
    }
    if (cell.attr("status") == "0") {
      var goods_ids = cell.attr("group_ids").split(",");
      for (i in goods_ids) {
        if (goods_ids[i] == single.attr("goods_id").split(",")[0]){
          toggleBooking(cell);
        }
       }
      }  
    });
}

var refreshPage = function(){
     location.reload();
};

function showConfirmOrder(th){
  var lock = false;
  var callback = function(){
    $('input[name=book_date]').val($(".current-book-date").attr('data'));
    
    //次票的时候选择单一商品的goods_id
    if ($("input[name=order_type]").val() == "1") {
      $('input[name=goods_id]').val($(th).attr("goods_id"));
    }
    $('.order_form').submit();
  };
  var num = $(".court-display>span.number").text();
  if (num == "0"){
    //请选择场次提示
    openCommonAlert('请选择场次');
  }else{
    if (!isLogin()) {
      openLoginDiglog(callback);
      return;          
    }
    
    checkOrderDueCount(callback);
  }
}

function insideJump(anchor){
 //$('#'+anchor).scrollintoview();
  var element = document.getElementById(anchor);
  var contentStartY;
  if($(window).scrollTop() < getElementTop(document.getElementById('booking')) - baseHeight){
    contentStartY = getElementTop(element) - baseHeight;
  } else {
    contentStartY = getElementTop(element);
  }
   
  // var contentStartY = $('#'+anchor).position().top-baseHeight;
 // $("html, body").animate({ scrollTop: contentStartY },500);
 $("html, body").scrollTop(contentStartY);

}

function refreshWithDate(business_id, cat_id, book_date){
   var requestParam = {
        'venues_id' : business_id,
        'cat_id':cat_id,
        't':book_date
      };

  $.ajax({
    type: "get",
    url: '/venues/getBookDateList?random='+ Math.random(),
    data: $.param(requestParam),
    timeout: 3000,
    success: function(data) {
      if(data.status == "0000") {
        //更新优惠活动列表
        $(".activityList").empty();
        var act_list = new Array();
        if (data.data.act_list != null && data.data.act_list.length > 0){
          for (i in data.data.act_list){
            var act = data.data.act_list[i];
            if (act.type != "1"){
              act_list.push(act);
            }
          }
        }
        
        if (act_list.length > 0){
          for( i in act_list){
            var act = act_list[i];
            $(".activityList").append('<span class=venuesActivity>'+act.act_name+'</span>');
          }
        } else {
          $(".activityList").remove();
          $(".activityTitle").remove();
        }

        //更新选场的风格
        $(".booking-date li.active").children().removeClass("active");
        $(".booking-date li.active").removeClass("active");
        $(".booking-date").find("[data-time="+data.data.book_date_list.book_date+"]").closest("li").addClass('active');
        $(".booking-date").find("[data-time="+data.data.book_date_list.book_date+"]").closest("li").children().addClass('active');
        //更新右侧选中框信息
        $(".court-display>span.number").text(0);
        $(".price-display>span.number").text('0元');
        $(".info>a.submit-button").removeClass("active");
        $(".append-msg").hide();
        $(".info li.none").show();
        $(".info li.court").remove();
        var ret = trans2WeekDayWithYear(data.data.book_date_list.book_date);
        $(".info dd.current-book-date").text(ret);
        $(".info dd.current-book-date").attr('data',data.data.book_date_list.book_date);

        //更新左侧选场信息
        $(".left-time-list>ul").empty();
        var hour_list = data.data.book_date_list.hour_list;
        var last_time = hour_list[hour_list.length-1].split(':')
        if (last_time[0] < 23){
          var last_hour = parseInt(last_time[0]) + 1;
          hour_list.push(last_hour+':'+last_time[1]);
        } else {
          hour_list.push('00:'+last_time[1]);
        }
        for(i in hour_list){
          $(".left-time-list>ul").append('<li class=hour>'+ hour_list[i] +'</li>');
        }

        // var hour_list = $(".left-time-list li.hour");

        // console.log("data.data:",data.data)
        $(".main-table>thead>tr").empty();
        for (i in data.data.course_list){
            var court = data.data.course_list[i];
            var theadStr = '<th class="heads"><span>'+court+'</span></th>'
            $(".main-table>thead>tr").append(theadStr);
        }
        
        var i = 0;

        $("tbody.main-table-body").empty();
        for (j in data.data.goods_list){
          var items = data.data.goods_list[j];
          $("tbody.main-table-body").append("<tr class=rows></tr>");
            var rows = $("http://www.quyundong.com/gosport/venues/js/tr.rows");
          // var cells = $(rows[i]).find("td");
          // $(rows[i]).empty();
            jQuery.each(items,function(k,item){
              var one_items = item.split(',') 
              var goods_id = one_items[0]
              var begin_time = one_items[1]
              var price = one_items[2]
              var status = one_items[3]
              var court_id = one_items[4]

              var place_holder;
              var spanStr;
              if (status == "0") {
                place_holder = data.data.course_list[court_id]+' '+ hour_list[i] +'-'+hour_list[i+1];
                spanStr = '<span class="can-order">￥'+ price +'</span>';
              }
              else{
                place_holder = '该场次已经售出';
                spanStr = '<span class="can-not-order"></span>';
              }
              
              var group_ids = "";
              jQuery.each(data.data.group_list,function(k,group){
                if (group.course_id == court_id){
                  var goods_ids = group.goods_ids.split(",");
                  jQuery.each(goods_ids,function(k,goods){
                  if (goods == goods_id){
                      group_ids = group.goods_ids;
                    }
                  })
                }
              })

              var cellStr = '<td class=single status="{0}" goods_id="{1}" court_name="{2}" place_holder="{3}" price="{4}" group_ids="{5}">{6}</td>'
              cellStr = cellStr.format(status,item,data.data.course_list[court_id],place_holder,price,group_ids,spanStr);
              $(rows[i]).append(cellStr);
             
            });
            i=i+1;         
          } 

          init();

      } 
    },
    error: function () {
      dismissLoading();
      openCommonAlert("失败，请稍后再试！");
    }
    });
}


function showBigMap(){
  $("#shadow").css({
    display: "block", height: $(document).height()
  });

  var $box = $('.bigMap');
  $box.css({
      display: "block"
  });

  var myOpts2 = {
    dom:$(".bigMap")[0],
    data:{
      centerX:$(".bigMap").attr("centerX"),
      centerY:$(".bigMap").attr("centerY"),
      setMapZooom:13
    }
  }
  var myMap2 = new UseAmap(myOpts2)
}

function activeTab(tab){
  $(".venues-tab li.tab").each(function(){
    if($(this).attr('data')==tab){
      if(!$(this).hasClass("active")){
        $(this).children().addClass("active");
        $(this).addClass("active");
      }
    }else {
    
      $(this).children().removeClass("active");
      $(this).removeClass("active");
    }
  });
}

//智能浮动函数
$.fn.smartFloat = function() {
    var position = function(element) {
        var top = getElementTop(element);
        element = $(element);
        $(window).scroll(function() {
            var scrolls = $(this).scrollTop();
            if (scrolls > top) {
                if (window.XMLHttpRequest) {
                  if(element.css("position") != "fixed"){
                    switch_tab_clicking = true;
                    element.css({position: "fixed", top: 0}); 
                  }
                } else {
                    element.css({top: scrolls});    
                }
            } else {
                element.css({position: "relative", top: 0});   
            }
        });
    };
    return $(this).each(function() {
        position(this);                         
    });
};    



